#!/bin/bash

# 检查 Ubuntu 版本
version=$(lsb_release -sc)
echo "当前 Ubuntu 版本是: $version"
case $version in
  "trusty" | "xenial" | "bionic" | "focal" | "jammy" | "mantic")
  ;;
  *)
    echo "错误：此脚本仅适用于 Ubuntu Trusty(14.04) / Xenial(16.04) / Bionic(18.04) / Focal(20.04) / Jammy(22.04) / Mantic(24.04)。退出。"
    exit 0
esac

# 删除无关的sources.list.d 备份现有的 sources.list
sudo find /etc/apt/sources.list.d/ -type f ! -name '*ros*' -exec rm {} \;
sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup

# 获取传入的镜像源选择参数，如果没有传参则使用清华源
mirror_choice=${1:-3} # 1) 163 2) 阿里 3) 清华 4) 中科大 5) 官方

# 根据选择设置镜像源
case $mirror_choice in
  1)
    mirror="mirrors.163.com"
    ;;
  2)
    mirror="mirrors.aliyun.com"
    ;;
  3)
    mirror="mirrors.tuna.tsinghua.edu.cn"
    ;;
  4)
    mirror="mirrors.ustc.edu.cn"
    ;;
  5)
    mirror="archive.ubuntu.com"
    ;;
  *)
    echo "无效选择。退出。"
    exit 1
    ;;
esac

# 更新 sources.list 文件
echo "
deb http://$mirror/ubuntu/ ${version} main restricted universe multiverse
deb http://$mirror/ubuntu/ ${version}-security main restricted universe multiverse
deb http://$mirror/ubuntu/ ${version}-updates main restricted universe multiverse
deb http://$mirror/ubuntu/ ${version}-proposed main restricted universe multiverse
deb http://$mirror/ubuntu/ ${version}-backports main restricted universe multiverse
deb-src http://$mirror/ubuntu/ ${version} main restricted universe multiverse
deb-src http://$mirror/ubuntu/ ${version}-security main restricted universe multiverse
deb-src http://$mirror/ubuntu/ ${version}-updates main restricted universe multiverse
deb-src http://$mirror/ubuntu/ ${version}-proposed main restricted universe multiverse
deb-src http://$mirror/ubuntu/ ${version}-backports main restricted universe multiverse
" | sudo tee /etc/apt/sources.list

# 更新软件包列表
echo "更新软件包列表..."
sudo apt-get update
sleep 1
